package com.yuzhitong.shapi.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.yuzhitong.shapi.R;
import com.yuzhitong.shapi.activity.WebPageActivity;
import a.a.a.MyApplication;
import com.yuzhitong.shapi.base.BaseMvpFragment;
import com.yuzhitong.shapi.base.Contents;
import com.yuzhitong.shapi.base.recycler.BaseAdapter;
import com.yuzhitong.shapi.base.recycler.BaseViewHolder;
import com.yuzhitong.shapi.bean.NavigationBean;
import com.yuzhitong.shapi.contract.NavigationContract;
import com.yuzhitong.shapi.presenter.NavigationPresenter;
import com.yuzhitong.shapi.util.AdUtilManage;
import com.yuzhitong.shapi.util.AppUtil;
import com.yuzhitong.shapi.util.GlideUtil;
import com.yuzhitong.shapi.util.UiUtil;
import com.yuzhitong.shapi.widget.AgreementDialog;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * Created by Brsya
 * CreateDate: 2022/3/24  22:30
 * Description:
 * 导航页
 */
public class NavigationFragment extends BaseMvpFragment<NavigationPresenter> implements NavigationContract.View {

    private LinearLayout llFragmentPage;
    private EditText etSearch;
    private LinearLayout llSearchIcon;
    private LinearLayout llHistoryDelete;
    private LinearLayout llHistoryListBox;
    private LinearLayout llHistoryBox;
    private ImageView ivNaviAd;
    private LinearLayout llMoreList;
    private RelativeLayout rlNaviAdBox;
    private LinearLayout agreementBox;

    private List<NavigationBean.LinkListDTO> historyList;
    // 屏幕高度
    private int heightPixels;
    // 软键盘是否显示
    private boolean imIsShow;
    /**
     * 服务器返回搜索url
     */
    private String searchUrl;

    private AgreementDialog dialog;

    private AdUtilManage adUtilManage;
    private long loadAdTime = 0;
    private RelativeLayout rlSearchInputBox;

    public static NavigationFragment newInstance() {

        Bundle args = new Bundle();

        NavigationFragment fragment = new NavigationFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public NavigationFragment() {

    }

    @Override
    protected void initPresenter() {
        presenter = new NavigationPresenter();
        presenter.attachView(this);
    }

    @Override
    protected void initData() {
        presenter.getSearchUrl(null);
        presenter.getNavigationList();

        loadAdTime = System.currentTimeMillis();
        adUtilManage = AdUtilManage.initShow(getActivity(), rlNaviAdBox, Contents.AD_TT_SDK_NAVIGATION_ID);
    }

    @Override
    protected void initView() {

        setContentViewId(R.layout.fragment_navigation);
        etSearch = (EditText) findViewById(R.id.et_search);
        rlNaviAdBox = (RelativeLayout) findViewById(R.id.rl_navi_ad_box);
        llHistoryDelete = (LinearLayout) findViewById(R.id.ll_history_delete);
        llHistoryListBox = (LinearLayout) findViewById(R.id.ll_history_list_box);
        llHistoryBox = (LinearLayout) findViewById(R.id.ll_history_box);
        ivNaviAd = (ImageView) findViewById(R.id.iv_navi_ad);
        llMoreList = (LinearLayout) findViewById(R.id.ll_more_list);
        llSearchIcon = findViewById(R.id.ll_search_icon);
        agreementBox = (LinearLayout) findViewById(R.id.agreement_box_na);
        rlSearchInputBox = (RelativeLayout) findViewById(R.id.rl_search_input_box);
        llFragmentPage = findViewById(R.id.ll_fragment_page);

        llFragmentPage.setPadding(
                llFragmentPage.getPaddingLeft(),
                llFragmentPage.getPaddingTop() + UiUtil.getStatusBarHeight(getContext()),
                llFragmentPage.getPaddingRight(),
                llFragmentPage.getPaddingBottom()
        );

        if (MyApplication.isOpenSearch()) {
            rlSearchInputBox.setVisibility(View.VISIBLE);
        }

        // 点击自动选中 xml中android:selectAllOnFocus="true"
        etSearch.setSelectAllOnFocus(true);
        etSearch.setOnEditorActionListener((textView, i, keyEvent) -> {
            // 搜索或回车
            if (i == EditorInfo.IME_ACTION_SEARCH || (keyEvent != null && keyEvent.getAction() == KeyEvent.KEYCODE_ENTER)) {
                String search = etSearch.getText().toString();
                handleSearchTet(search);
                return true;
            }
            return false;
        });
        //        ivNaviAd.setVisibility(MyApplication.isOpenAd() ? View.VISIBLE : View.GONE);

        llHistoryDelete.setOnClickListener(view -> {
            if (historyList != null) {
                historyList.clear();
                refreshHistory();
            }
        });

        llSearchIcon.setOnClickListener((v) -> {
            String search = etSearch.getText().toString();
            handleSearchTet(search);
        });


        // 加载本地历史记录
        String historyListStr = MyApplication.aCache.getAsString(Contents.CACHE_KEY_HISTORY_LIST);
        if (historyListStr != null) {
            historyList = JSON.parseArray(historyListStr, NavigationBean.LinkListDTO.class);
        }
        if (historyList == null) {
            historyList = new LinkedList<>();
        }
        refreshHistory();

        // 获取屏幕宽度
        WindowManager manager = Objects.requireNonNull(getActivity()).getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        heightPixels = outMetrics.heightPixels;

        etSearch.getViewTreeObserver().addOnGlobalLayoutListener(() -> {

            //获取当前根视图在屏幕上显示的大小
            Rect r = new Rect();
            etSearch.getWindowVisibleDisplayFrame(r);

            // 判断是否显示键盘
            if (heightPixels - r.bottom > 300) {
                imIsShow = true;
            }
            // 判断显示高度是否等于屏幕高度  键盘显示转为隐藏
            if (heightPixels == r.bottom && imIsShow) {
                imIsShow = false;
                etSearch.clearFocus();
            }

        });


        agreementBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog == null) {
                    dialog = new AgreementDialog(getContext());
                }
                dialog.show();
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            refreshHistory();

            if (System.currentTimeMillis() - loadAdTime > Contents.AD_SHOW_TIME) {
                loadAdTime = System.currentTimeMillis();
                if (adUtilManage != null) {
                    AdUtilManage.destroy(adUtilManage);
                }
                adUtilManage = AdUtilManage.initShow(getActivity(), rlNaviAdBox, Contents.AD_TT_SDK_NAVIGATION_ID);
            }
        }
    }

    @Override
    public void onDestroyView() {
        AdUtilManage.destroy(adUtilManage);
        super.onDestroyView();
    }

    private void refreshHistory() {

        MyApplication.aCache.put(Contents.CACHE_KEY_HISTORY_LIST, JSON.toJSONString(historyList));
        if (historyList == null || historyList.size() == 0) {
            llHistoryBox.setVisibility(View.GONE);
        } else {
            llHistoryBox.setVisibility(View.VISIBLE);
        }

        llHistoryListBox.removeAllViews();
        for (int i = 0; i < historyList.size() && i < 5; i++) {
            addNavigation(llHistoryListBox, historyList.get(i));
        }
    }

    @Override
    public void searchUrl(String url) {
        searchUrl = url;
        MyApplication.aCache.put(Contents.CACHE_KEY_SEARCH_URL, url);
    }

    @Override
    public void searchUrlEmpty() {
        searchUrl = null;
        MyApplication.aCache.put(Contents.CACHE_KEY_SEARCH_URL, "");
    }

    @Override
    public void showNavigationList(List<NavigationBean> navigationBeans) {
        for (NavigationBean navigationBean : navigationBeans) {
            addMore(llMoreList, navigationBean);
        }
    }

    /**
     * 添加导航
     *
     * @param boxView        需要添加到的View
     * @param navigationBean 数据
     */
    private void addNavigation(LinearLayout boxView, NavigationBean.LinkListDTO navigationBean) {
        LinearLayout linearLayout = (LinearLayout) View.inflate(getContext(), R.layout.layout_navigation_box, null);
        ImageView icon = linearLayout.findViewById(R.id.iv_navi_icon);
        TextView textView = linearLayout.findViewById(R.id.tv_navi_text);
        GlideUtil.loadCircle(icon, navigationBean.getIconUrl());
        textView.setText(navigationBean.getName());

        linearLayout.setOnClickListener(view -> {
            gotoWebPage(navigationBean.getLinkUrl());
            addNavigationBean(navigationBean);
        });

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                UiUtil.dpToPx(Objects.requireNonNull(getContext()), 64)
                , LinearLayout.LayoutParams.MATCH_PARENT);
        boxView.addView(linearLayout, layoutParams);
    }

    private void addNavigationBean(NavigationBean.LinkListDTO navigationBean) {

        for (int i = historyList.size() - 1; i >= 0; i--) {
            if (navigationBean.getId().equals(historyList.get(i).getId())) {
                historyList.remove(i);
            }
        }

        if (historyList.size() >= 5) {
            historyList.remove(historyList.size() - 1);
        }
        historyList.add(0, navigationBean);
    }

    /**
     * 添加功能区
     *
     * @param boxView        需要添加到的View
     * @param navigationBean 数据
     */
    private void addMore(LinearLayout boxView, NavigationBean navigationBean) {
        if (navigationBean == null || navigationBean.getLinkList() == null) {
            return;
        }


        int spanCount = 4;
        LinearLayout linearLayout = (LinearLayout) View.inflate(getContext(), R.layout.layout_more_box, null);
        TextView textView = linearLayout.findViewById(R.id.tv_title);
        textView.setText(navigationBean.getName());

        RecyclerView recyclerView = linearLayout.findViewById(R.id.rv_find_list);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), spanCount));
        BaseAdapter<NavigationBean.LinkListDTO> adapter = new BaseAdapter<NavigationBean.LinkListDTO>() {
            @Override
            public BaseViewHolder onCreate(ViewGroup parent, int viewType) {
                View rootView = LayoutInflater.from(getContext()).inflate(R.layout.layout_navigation_box, parent, false);
                ViewGroup.LayoutParams layoutParams = rootView.getLayoutParams();
                if (layoutParams == null) {
                    layoutParams = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                } else {
                    layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                }
                rootView.setPadding(
                        rootView.getPaddingLeft(),
                        rootView.getPaddingTop(),
                        rootView.getPaddingRight(),
                        rootView.getPaddingBottom() + UiUtil.dpToPx(getContext(), 15)

                );

                rootView.setLayoutParams(layoutParams);
                return new BaseViewHolder(rootView);
            }

            @Override
            public void onBind(BaseViewHolder viewHolder, int RealPosition, NavigationBean.LinkListDTO data) {
                ImageView icon = viewHolder.findViewById(R.id.iv_navi_icon);
                TextView textView = viewHolder.findViewById(R.id.tv_navi_text);
                GlideUtil.loadCircle(icon, data.getIconUrl());
                textView.setText(data.getName());
            }
        };
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener((position, data) -> {
            gotoWebPage(data.getLinkUrl());
            addNavigationBean(data);
        });
        adapter.setDataList(navigationBean.getLinkList());


        int size;
        if (navigationBean.getLinkList().size() % spanCount == 0) {
            size = navigationBean.getLinkList().size() / spanCount;
        } else {
            size = (navigationBean.getLinkList().size() / spanCount) + 1;
        }
        LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) recyclerView.getLayoutParams();
        layoutParams1.height = UiUtil.dpToPx(Objects.requireNonNull(getContext()), 84 * size);
        recyclerView.setLayoutParams(layoutParams1);

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        boxView.addView(linearLayout, layoutParams);
    }

    /**
     * 处理搜索框内容
     *
     * @param text 搜索框内容
     */
    private void handleSearchTet(String text) {
        String url = AppUtil.handleSearchText(searchUrl, text);
        if (url == null) {
            return;
        }
        gotoWebPage(url);
    }


    /**
     * 加载网页
     *
     * @param url 网页地址
     */
    private void gotoWebPage(String url) {
        Intent intent = new Intent(getActivity(), WebPageActivity.class);
        intent.putExtra(Contents.INTENT_H5_URL, url);
        startActivity(intent);
    }
}
